import socket


class TCPServer:

    def __init__(self, server_address, HandlerClass):
        self.server_address = server_address
        self.HandlerClass = HandlerClass
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.is_shutdown = False
        pass

    def serve_forver(self):
        self.socket.bind(self.server_address)
        self.socket.listen(10)
        while not self.is_shutdown:
            # 接受请求
            requset, client_address = self.get_request()
            # 处理请求
            try:
                self.process_request(requset, client_address)
            except Exception as e:
                print(e)
            finally:
                # 关闭链接
                self.close_request(requset)
        pass

    def get_request(self):
        return self.socket.accept()

    def process_request(self, requset, client_address):
        handler = self.HandlerClass(requset, client_address)
        handler.handle()

    def close_request(self, requset):
        requset.shutdown()
        requset.close()

    def shutdown(self):
        self.is_shutdown = True
        pass
